var createError = require('http-errors');   // 错误中间件
var express = require('express');
var cookieParser = require('cookie-parser');    // cookie
var logger = require('morgan');             // 日志中间件
var session = require('express-session');
// var FileStore = require('session-file-store')(session);
var router = require('./routes/router');
const { portConfig, sessionConfig } = require('./productionConfig')


var app = express();

// 挂载第三方中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// app.use(express.static(path.join(__dirname, 'public')));

//session
app.use(session({
    name: sessionConfig.name,
    secret: sessionConfig.secret, // 用来对session id相关的cookie进行签名

    // store: new FileStore(), // 本地存储session（文本文件，也可以选择其他store，比如redis的）

    saveUninitialized: false, // 是否自动保存未初始化的会话，建议false
    resave: false, // 是否每次都重新保存会话，建议false
    cookie: {
        maxAge: 4 * 60 * 60 * 1000 // 有效期4小时，单位是毫秒
    }
}));
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});

// 路由中间件
app.use('/', router);

// 接住404并转发到第三方错误处理中间件
app.use(function (req, res, next) {
    next(createError(404));
});

// 错误处理中间件
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    res.status(err.status || 500);
    res.send('error')
});

app.listen(portConfig)
console.log('foril_blog server running on port:', portConfig)
console.log('Forever, foriL');
